package cn.e3.search.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import search.SearchItem;
import search.SearchResult;
/*
 * 抽取搜索代码
 */
@Repository
public class SearchResultDao {
	@Autowired
	private SolrServer solrServer;
	/*
	 * 封装查询条件，用户将查询条件接入
	 */
	public SearchResult search(SolrQuery solrQuery) throws Exception{
		//开始查询
		QueryResponse queryResponse = solrServer.query(solrQuery);
		//得到查询结果
		SolrDocumentList solrDocumentList = queryResponse.getResults();
		//去高亮显示
		Map<String, Map<String, List<String>>> map = queryResponse.getHighlighting();
		//得到查询得到的总记录数
		long numFound = solrDocumentList.getNumFound();
		//创键集合，咋混给pojo
		List<SearchItem> list=new ArrayList<SearchItem>();
		//遍历查询结果，将结果封装到pojo中
		for (SolrDocument solrDocument : solrDocumentList) {
			//创建pojo对象
			SearchItem searchItem=new SearchItem();
			//取出封装id
			searchItem.setId((String) solrDocument.get("id"));
			//封装
			searchItem.setCategory_name((String) solrDocument.get("item_category_name"));
			//封装卖点
			searchItem.setSell_point((String) solrDocument.get("item_sell_point"));
			//封装价格
			searchItem.setPrice((Long) solrDocument.get("item_price"));
			//高亮显示，让标题高亮显示
			List<String> list2 = map.get(solrDocument.get("id")).get("item_title");
			//判断list2是否为空
			String title="";
			if(list2!=null&&list2.size()>0){
				 title = list2.get(0);
			}else{
				title=(String) solrDocument.get("item_title");
			}
			//封装title
			searchItem.setTitle(title);
			//封装iamge
			searchItem.setImage((String) solrDocument.get("item_image"));
			list.add(searchItem);
		}
		//创建返回的searchresult对象
		SearchResult searchResult=new SearchResult();
		searchResult.setRecordCount(numFound);
		searchResult.setList(list);
		return searchResult;
	}
}
